#!/bin/sh

migrate_data_to_s3 () {
  BUCKET="${1:-registry-data}"

  if [ -z "${BUCKET}" ]; then return 1; fi

  if [ -n "${DOCKER_HOST}" ]; then
      log "Using docker host: ${DOCKER_HOST}"
      export DOCKER_HOST="${DOCKER_HOST}"
  fi

  REGISTRY_CONTAINER="$(docker ps | grep registry_ | awk '{print $1}')"
  S3_CONTAINER="$(docker ps | grep s3_ | awk '{print $1}')"

  if [ -z "${REGISTRY_CONTAINER}" ] || [ -z "${S3_CONTAINER}" ]; then return 2; fi

  REGISTRY_VOLUME="$(docker inspect "${REGISTRY_CONTAINER}" | jq -r '.[].Mounts | map(select(.Destination=="/data")) | .[0].Source')"
  S3_VOLUME=$(docker inspect "${S3_CONTAINER}" | jq -r '.[].Mounts | map(select(.Destination=="/export")) | .[0].Source')

  if [ -z "${REGISTRY_VOLUME}" ] || [ -z "${S3_VOLUME}" ]; then return 3; fi

  # run the S3 container image, and copy the data partition into S3...
  docker run -it --rm \
      -v "${REGISTRY_VOLUME}:/data" \
      -v "${S3_VOLUME}:/s3" \
      --name "migrate-registry" alpine \
      sh -c "mkdir -p /s3/${BUCKET}/data && cp -r /data/docker /s3/${BUCKET}/data/"
}
